import { reactive, ref, watch } from 'vue'
import draggable from 'vuedraggable'

function useDragToScroll(
    dragEle: HTMLElement,
    scrollable: HTMLElement,
    initialState: {
        enabled: boolean
    } = {
        enabled: true,
    },
) {
    

    const enable = ref(true)
    enable.value = initialState.enabled

    const isDragging = ref(false)
    const offset = reactive({
        x: 0,
        y: 0,
    })

    dragEle.addEventListener('mousedown', function (e) {
        if (!enable.value) {
            return false
        }

        isDragging.value = true
        offset.x = e.clientX - dragEle.getBoundingClientRect().left
        offset.y = e.clientY - dragEle.getBoundingClientRect().top
    })

    scrollable.addEventListener('mousemove', function (e) {
        if (!enable.value) {
            return false
        }

        if (isDragging.value) {
            const x = e.clientX - offset.x
            const y = e.clientY - offset.y

            dragEle.style.left = x + 'px'
            dragEle.style.top = y + 'px'

            // 判断是否需要滚动
            const scrollX = x > scrollable.clientWidth - dragEle.clientWidth
            const scrollY = y > scrollable.clientHeight - dragEle.clientHeight

            if (scrollX || scrollY) {
                scrollable.scrollLeft = scrollX
                    ? scrollable.scrollLeft + 5
                    : scrollable.scrollLeft
                scrollable.scrollTop = scrollY
                    ? scrollable.scrollTop + 5
                    : scrollable.scrollTop
            }
        }
    })

    dragEle.addEventListener('mouseup', function () {
        if (!enable.value) {
            return false
        }

        isDragging.value = false
    })

    return {
        isDragging,
        offset,
        enable,
    }
}

export default useDragToScroll
